/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: swx  Date: 2019-03-21 Time: 15:16
 *
 * 工单列表
 */


import React, {Component} from 'react';
import {
    SafeAreaView,
    View,
    Text,
    TouchableOpacity,
    Modal, FlatList, Image,
} from 'react-native';
import {connect} from 'react-redux';
import {styles} from "../ImmediateOrderScreen/ImmediateOrderScreen.Style";
import {getDs} from "../DepartmentalRepairOrderScreen/Actions";
import {FetchStatus} from "../../../../configuration/RequestConfiguration";
import {COLOR_WHITE} from "../../../../constant/PHColors";
import AntDesign from "react-native-vector-icons/AntDesign";
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
import DividingLineViewComponent from "../../../../component/DividingLineViewComponent/DividingLineViewComponent";
import User from "../../../../model/User/User";
import DatePicker from "react-native-datepicker";


class ImmediateOrderScreen extends Component {

    static navigationOptions = ({navigation}) => ({
        title: '工单列表',
        headerRight: (
            <TouchableOpacity activeOpacity={0.9} onPress={navigation.getParam('setSelectModalVisible')}>
                <View style={{ height: 44,paddingRight:10, flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center'}}>
                    <Text style={{fontSize: 16, color: '#212121'}}>
                        {navigation.getParam('selectModalValue')}
                        <AntDesign name={'down'} size={15} style={{color: '#212121',marginLeft: 5}}/>
                    </Text>
                </View>
            </TouchableOpacity>
        )
    });

    //构造
    constructor(props) {
        super(props);

        this.state = {
            userid:"",
            defaultMsg:[],
            selectStatus:[],
            selectRole:[],
            selectArea:[],
            selectValue:{"status":"","role":"","area":"","work_userid":"","create_user":"","startdate":"","enddate":""},
            showFoot:0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            pageNo: 1,//当前第几页
            totalPage:0,//总的页数
            itemNo:20,//item的个数
            recordNum:0,//数据总条数
            selectModal:false,
            selectModalValue:this.props.navigation.getParam("status")?this.props.navigation.getParam("status"):'处理中',
            condition:this.props.navigation.getParam("condition")?this.props.navigation.getParam("condition"):{},
            refreshing:false,//下拉刷新
        };
    }

    componentWillMount() {
        this.props.navigation.setParams({setSelectModalVisible: this._setSelectModalVisible,selectModalValue:this.state.selectModalValue});
    }

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;

        if (nextProps.onGetDs !== this.props.onGetDs && nextProps.onGetDs.fetchStatus === FetchStatus.Success) {
            let defaultInfo = nextProps.onGetDs.rows;
            this.state.showFoot = 0;
            if(this.state.pageNo>=nextProps.onGetDs.total){
                this.state.showFoot = 1;//listView底部显示没有更多数据了
            }
            if(this.state.pageNo===1){
                defaultInfo = nextProps.onGetDs.rows
            }else{
                defaultInfo = this.state.defaultMsg.concat(defaultInfo)
            }
            this.setState({
                defaultMsg: defaultInfo,
                totalPage:nextProps.onGetDs.total,
                recordNum:nextProps.onGetDs.records,
                itemNo:20,//item的个数
                refreshing:false,
            });
        }
    }

    // 组件渲染后调用
    componentDidMount() {
        let _this = this;
        this.setState({
            pageNo:1,
        });
        // this.props.navigation.navigate('MainNavigator');

        this.state.selectValue.status = this.state.selectModalValue;

        User.getUser(user => {
            if (user&&user.token) {
                this.state.userid = user.userid;
                let {dispatch} = this.props;
                if(this.state.selectValue.status==="待验收"){
                    this.state.selectValue.work_userid = '';
                    this.state.selectValue.create_user = '';
                    this.state.selectValue.type = '验收'
                }else if(this.state.selectValue.status==="待复核"){
                    this.state.selectValue.work_userid = '';
                    this.state.selectValue.create_user = '';
                    this.state.selectValue.type = '复核'
                }else{
                    this.state.selectValue.work_userid = user.userid;
                    this.state.selectValue.create_user = '';
                    this.state.selectValue.type = ''
                }
                let str = {"arg":{"SQLfields":"sn,status,object_name,type,recordno,area_fullname,object_fullname,create_datetime,report_username,report_connect,remark"},"where":{...this.state.selectValue,...this.state.condition}};
                dispatch(getDs(JSON.stringify(str),this.state.pageNo));
            }
        })

    }

    render(){
        return(
            <SafeAreaView style={styles.body}>

                <View style={styles.body}>
                    <View style={styles.headerContainer}>
                        <Text style={styles.headerText}>
                            共{this.state.recordNum?this.state.recordNum:'0'}张单
                        </Text>

                        <View style={styles.itemHeaderRight}>
                            <DatePicker
                                style={{width: 90,alignItems:'flex-end',justifyContent:'center',}}
                                date={this.state.selectValue.startdate}
                                showIcon={false}
                                mode="date"
                                placeholder="开始时间"
                                format={"YYYYMMDD"}
                                confirmBtnText="确定"
                                cancelBtnText="取消"
                                customStyles={{
                                    dateIcon: {
                                        position: 'absolute',
                                        left: 0,
                                        top: 0,
                                        marginLeft: 0
                                    },
                                    dateInput: {
                                        marginLeft: 0,
                                        borderWidth: 0,
                                        fontSize:15,
                                        marginRight: 0,
                                    }
                                }}
                                onDateChange={(date) => {
                                    this.state.selectValue.startdate = date;
                                    // this.setState({cleanTime: date})
                                    this._search()
                                }}
                                onCloseModal={(res)=>{
                                    this.state.selectValue.startdate = '';
                                    this._search()
                                }}
                            />
                            <Text> - </Text>
                            <DatePicker
                                style={{width: 90,alignItems:'flex-end',justifyContent:'center',}}
                                date={this.state.selectValue.enddate}
                                showIcon={false}
                                mode="date"
                                placeholder="结束时间"
                                format={"YYYYMMDD"}
                                confirmBtnText="确定"
                                cancelBtnText="取消"
                                customStyles={{
                                    dateIcon: {
                                        position: 'absolute',
                                        left: 0,
                                        top: 0,
                                        marginLeft: 0
                                    },
                                    dateInput: {
                                        marginLeft: 0,
                                        borderWidth: 0,
                                        fontSize:15,
                                        marginRight: 0,
                                    }
                                }}
                                onDateChange={(date) => {
                                    this.state.selectValue.enddate = date;
                                    // this.setState({cleanTime: date})
                                    this._search()
                                }}
                                onCloseModal={(res)=>{
                                    this.state.selectValue.enddate = '';
                                    this._search()
                                }}
                            />
                        </View>
                    </View>
                    <FlatList
                        data = {this.state.defaultMsg}
                        onRefresh = {this._onRefresh.bind(this)} //刷新操作
                        refreshing = {this.state.refreshing}
                        renderItem={this._renderItem}
                        ListFooterComponent={this._renderFooter.bind(this)}
                        onEndReachedThreshold={0.1}
                        keyExtractor={(item, index) => index.toString()}
                        onEndReached={this._onEndReached.bind(this)}
                    />
                </View>

                <Modal onRequestClose={()=> this._onRequestClose()} transparent={true} visible={this.state.selectModal}>
                    <TouchableOpacity style={{flex: 1}} activeOpacity={1} onPress={this._setSelectModalVisible}>
                        <View style={styles.modalContainer}>
                            <View style={styles.modalView}>
                                <View style={styles.modalHeader}>
                                    <Text style={styles.modalHeaderText}>
                                        工单状态
                                    </Text>
                                </View>

                                <TouchableOpacity style={styles.modalItemView} activeOpacity={0.8} onPress={() => {
                                    this._setSelectModalVisible();
                                    this._setSelectModalValue("所有状态");
                                }}>
                                    <View style={styles.modalItemViewLeft}>
                                        <Text style={styles.modalItemText}>
                                            所有状态
                                        </Text>
                                    </View>
                                    {this._selectModalValue("所有状态")}
                                </TouchableOpacity>

                                <DividingLineViewComponent lineHeight={1}/>

                                <TouchableOpacity style={styles.modalItemView} activeOpacity={0.8} onPress={() => {
                                    this._setSelectModalVisible();
                                    this._setSelectModalValue("未派工");
                                }}>
                                    <View style={styles.modalItemViewLeft}>
                                        <Text style={styles.modalItemText}>
                                            未派工
                                        </Text>
                                    </View>
                                    {this._selectModalValue("未派工")}
                                </TouchableOpacity>

                                <DividingLineViewComponent lineHeight={1}/>

                                <TouchableOpacity style={styles.modalItemView} activeOpacity={0.8} onPress={() => {
                                    this._setSelectModalVisible();
                                    this._setSelectModalValue("处理中");
                                }}>
                                    <View style={styles.modalItemViewLeft}>
                                        <Text style={styles.modalItemText}>
                                            处理中
                                        </Text>
                                    </View>
                                    {this._selectModalValue("处理中")}
                                </TouchableOpacity>

                                <DividingLineViewComponent lineHeight={1}/>

                                <TouchableOpacity style={styles.modalItemView} activeOpacity={0.8} onPress={() => {
                                    this._setSelectModalVisible();
                                    this._setSelectModalValue("待验收");
                                }}>
                                    <View style={styles.modalItemViewLeft}>
                                        <Text style={styles.modalItemText}>
                                            待验收
                                        </Text>
                                    </View>
                                    {this._selectModalValue("待验收")}
                                </TouchableOpacity>

                                <DividingLineViewComponent lineHeight={1}/>

                                <TouchableOpacity style={styles.modalItemView} activeOpacity={0.8} onPress={() => {
                                    this._setSelectModalVisible();
                                    this._setSelectModalValue("待复核");
                                }}>
                                    <View style={styles.modalItemViewLeft}>
                                        <Text style={styles.modalItemText}>
                                            待复核
                                        </Text>
                                    </View>
                                    {this._selectModalValue("待复核")}
                                </TouchableOpacity>

                                <DividingLineViewComponent lineHeight={1}/>

                                <TouchableOpacity style={styles.modalItemView} activeOpacity={0.8} onPress={() => {
                                    this._setSelectModalVisible();
                                    this._setSelectModalValue("完成");
                                }}>
                                    <View style={styles.modalItemViewLeft}>
                                        <Text style={styles.modalItemText}>
                                            完成
                                        </Text>
                                    </View>
                                    {this._selectModalValue("完成")}
                                </TouchableOpacity>

                                <DividingLineViewComponent lineHeight={1}/>

                                <TouchableOpacity style={styles.modalItemView} activeOpacity={0.8} onPress={() => {
                                    this._setSelectModalVisible();
                                    this._setSelectModalValue("拒绝");
                                }}>
                                    <View style={styles.modalItemViewLeft}>
                                        <Text style={styles.modalItemText}>
                                            拒绝
                                        </Text>
                                    </View>
                                    {this._selectModalValue("拒绝")}
                                </TouchableOpacity>

                                <DividingLineViewComponent lineHeight={1}/>

                                <TouchableOpacity style={styles.modalBottomView} activeOpacity={0.8} onPress={() => {
                                    this._setSelectModalVisible();
                                }}>
                                    <View style={styles.modalBottomView}>
                                        <Text style={styles.modalBottomText}>
                                            返回
                                        </Text>
                                    </View>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </TouchableOpacity>
                </Modal>
            </SafeAreaView>
        )
    }

    //下拉刷新,更改状态，重新获取数据
    _onRefresh(){
        this.setState({
            refreshing:true,
            defaultMsg:[]
        },()=>{
            this.state.pageNo=1;
            let {dispatch} = this.props;
            let str = {"arg":{"SQLfields":"sn,status,object_name,type,recordno,area_fullname,object_fullname,create_datetime,report_username,report_connect,remark"},"where":{...this.state.selectValue,...this.state.condition}};
            dispatch(getDs(JSON.stringify(str),this.state.pageNo))
        });
    }

    //列表内容循环
    _renderItem = ({ item }) => {
        let _this=this;
        return (
            <TouchableOpacity activeOpacity={0.8} onPress={() => {
                this.props.navigation.navigate('DepartmentalRepairOrderDetailScreen',{"sn":item.sn,"beforePage":"ImmediateOrderScreen",callBack:()=>{
                        let {dispatch} = _this.props;
                        let str = {"arg":{"SQLfields":"sn,status,object_name,type,recordno,area_fullname,object_fullname,create_datetime,report_username,report_connect,remark"},"where":{..._this.state.selectValue,..._this.state.condition}};
                        dispatch(getDs(JSON.stringify(str),_this.state.pageNo))
                    }})
            }}>
                <View style={styles.boxBody} onPress={()=>{

                }}>
                    <View style={styles.top}>
                        <View style={styles.topLeft}>
                            <Text style={styles.topPointText}>
                                {item.object_fullname ? (item.object_fullname.length > 10 ? item.object_fullname.substr(0, 10) + "..." : item.object_fullname) : ""}
                            </Text>
                        </View>
                        <View style={styles.topRight}>
                            {item.type==="紧急维修"?<Text style={styles.topFromTextRed}>{item.type}</Text>:<Text style={styles.topFromTextBlue}>{item.type}</Text>}
                        </View>
                    </View>

                    <View style={styles.center}>
                        <Text style={styles.centerText}>
                            {item.area_fullname ? (item.area_fullname.length > 17 ? item.area_fullname.substr(0, 17) + "..." : item.area_fullname) : ""}
                        </Text>
                    </View>

                    <View style={[styles.center,{marginTop:1}]}>
                        <Text style={styles.centerText}>
                            {item.remark ? (item.remark.length > 100 ? item.remark.substr(0, 100) + "..." : item.remark) : ""}
                        </Text>
                    </View>

                    <View style={styles.bottom}>
                        <Text style={styles.bottomText}>
                            {item.create_datetime}
                        </Text>
                    </View>
                </View>
            </TouchableOpacity>
        )
    };

    _selectModalValue = (value) => {
        if(this.state.selectModalValue===value){
            return(
                <View style={styles.modalItemViewRight}>
                    <MaterialCommunityIcons name={'radiobox-marked'} size={25} />
                </View>
            )
        }else{
            return(
                <View style={styles.modalItemViewRight}>
                    <MaterialCommunityIcons name={'radiobox-blank'} size={25} />
                </View>
            )
        }
    };

    _setSelectModalValue = (value) =>{
        this.setState({selectModalValue:value,pageNo:1,});
        this.props.navigation.setParams({selectModalValue:value});

        //获取数据
        if(value==="所有状态"){
            this.state.selectValue.status = "";
            this.state.selectValue.work_userid = this.state.userid;
            this.state.selectValue.create_user = '';
            this.state.selectValue.type = ''
        }else{
            this.state.selectValue.status = value;

            if(value==="待验收"){
                this.state.selectValue.work_userid = '';
                this.state.selectValue.create_user = '';
                this.state.selectValue.type = '验收'
            }else if(this.state.selectValue.status==="待复核"){
                this.state.selectValue.work_userid = '';
                this.state.selectValue.create_user = '';
                this.state.selectValue.type = '复核'
            }else{
                this.state.selectValue.work_userid = this.state.userid;
                this.state.selectValue.create_user = '';
                this.state.selectValue.type = ''
            }


        }
        // this.state.selectValue.work_userid = this.props.onLogin.userid;
        this.state.pageNo = 1;
        let {dispatch} = this.props;
        let str = {"arg":{"SQLfields":"sn,status,object_name,type,recordno,area_fullname,object_fullname,create_datetime,report_username,report_connect,remark"},"where":{...this.state.selectValue,...this.state.condition}};
        dispatch(getDs(JSON.stringify(str),this.state.pageNo))
    }

    _search = () =>{
        this.setState({pageNo:1,});

        this.state.pageNo = 1;
        let {dispatch} = this.props;
        let str = {"arg":{"SQLfields":"sn,status,object_name,type,recordno,area_fullname,object_fullname,create_datetime,report_username,report_connect,remark"},"where":{...this.state.selectValue,...this.state.condition}};
        dispatch(getDs(JSON.stringify(str),this.state.pageNo))
    }

    _setSelectModalVisible = () => {
        this.setState({
            selectModal:!this.state.selectModal
        })
    };

    _onRequestClose(){
        this.setState({
            selectModal:false
        })
    }

    _onEndReached(){
        //如果是正在加载中或没有更多数据了，则返回
        if(this.state.showFoot !== 0 ){
            return ;
        }
        //如果当前页大于或等于总页数，那就是到最后一页了，返回
        if((this.state.pageNo!==1) && (this.state.pageNo>=this.state.totalPage)){
            return;
        } else {
            this.state.pageNo++;
        }
        //底部显示正在加载更多数据
        this.state.showFoot=2;

        //获取数据
        if(this.state.selectModalValue==="所有状态"){
            this.state.selectValue.status = "";
            this.state.selectValue.work_userid = this.state.userid;
            this.state.selectValue.create_user = '';
            this.state.selectValue.type = ''
        }else{
            this.state.selectValue.status = this.state.selectModalValue;
            if(this.state.selectValue.status==="待验收"){
                this.state.selectValue.work_userid = '';
                this.state.selectValue.create_user = '';
                this.state.selectValue.type = '验收'
            }else if(this.state.selectValue.status==="待复核"){
                this.state.selectValue.work_userid = '';
                this.state.selectValue.create_user = '';
                this.state.selectValue.type = '复核'
            }else{
                this.state.selectValue.work_userid = this.state.userid;
                this.state.selectValue.create_user = '';
                this.state.selectValue.type = ''
            }
        }
        // this.state.selectValue.work_userid = this.props.onLogin.userid;
        let {dispatch} = this.props;
        let str = {"arg":{"SQLfields":"sn,status,object_name,type,recordno,area_fullname,object_fullname,create_datetime,report_username,report_connect,remark"},"where":{...this.state.selectValue,...this.state.condition}};
        dispatch(getDs(JSON.stringify(str),this.state.pageNo))
    }

    _renderFooter(){
        if (this.state.showFoot === 1) {
            return (
                <View style={{height:30,alignItems:'center',justifyContent:'flex-start',}}>
                    <Text style={{color:'#999999',fontSize:14,marginTop:5,marginBottom:5,}}>
                        没有更多数据了
                    </Text>
                </View>
            );
        } else if(this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    {/*<ActivityIndicator />*/}
                    <Text>正在加载更多数据...</Text>
                </View>
            );
        } else if(this.state.showFoot === 0){
            return (
                <View style={styles.footer}>
                    <Text>

                    </Text>
                </View>
            );
        }
    }
}


const props = state => {
    return {
        onGetDs: state.onGetDs,
        onLogin: state.onLogin
    }
};

export default ImmediateOrderScreen = connect(props)(ImmediateOrderScreen);